package rrrmai.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.Toast;

import com.jakewharton.rxbinding2.support.v7.widget.RxToolbar;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxCheckedTextView;
import com.jakewharton.rxbinding2.widget.RxCompoundButton;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jakewharton.rxbinding2.widget.TextViewAfterTextChangeEvent;
import com.xgggh.rrrmai.BR;
import com.xgggh.rrrmai.R;
import com.xgggh.rrrmai.databinding.ActivityPostBinding;
import com.xgggh.rrrmai.databinding.ActivityWorthBinding;

import org.reactivestreams.Publisher;

import java.util.UUID;
import java.util.concurrent.Callable;

import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import rrrmai.model.Rsp;
import rrrmai.service.PostService;
import rrrmai.viewbinder.Comment;
import rrrmai.viewbinder.Post;
import rrrmai.viewmodel.PostsViewModel;
import xgggh.activity.BaseActivity;
import xgggh.manage.AuthManager;

/**
 * @title  设置价值　dialog化
 */
public class WorthActivity extends BaseActivity {
    ActivityWorthBinding mBinding;
    Comment mComment  = new Comment();
    PostsViewModel mPostsVm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding=DataBindingUtil.setContentView(this,R.layout.activity_worth);
        setSupportActionBar(mBinding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        Comment _comment= getIntent().getParcelableExtra("data");
        if (_comment!=null){
            mComment=_comment;
        }
        mBinding.setVariable(BR.comment,mComment);

        mPostsVm=getPostViewModelProvider();
        onClick();
        onListener();
    }

    private  void onListener(){
        RxToolbar.itemClicks(mBinding.toolbar)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindToLifecycle())
                .subscribe(menuItem -> {
                    int itemId=menuItem.getItemId();
                    switch (itemId){
                        case R.id.action_send:
                            actionSend();
                            break;
                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_send,menu);
        return true;
    }

    private void actionSend(){
        //checklist
        boolean pass=checkList();
        if (!pass){
            return;
        }
        //close input method
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mBinding.getRoot().getWindowToken(), 0);
        //dialog
        new AlertDialog.Builder(this)
                .setTitle("确认")
                .setMessage("确认发送？")
                .setPositiveButton("ok", (dialog, which) -> {
                    sendComment();
                    dialog.dismiss();
                })
                .setNegativeButton("cancel",(dialog, which) -> {
                    dialog.dismiss();
                })
                .setCancelable(true)
                .setOnDismissListener(null)
                .setOnCancelListener(null)
                .create()
                .show();
    }


    private boolean checkList(){
        boolean checked=true;
        if (TextUtils.isEmpty(mComment.getContent())){
            Toast.makeText(this, "内容不能为空", Toast.LENGTH_SHORT).show();
            checked=false;
        }else if (TextUtils.isEmpty(mComment.getUserMobile())){
            Toast.makeText(this, "评价对象不能为空", Toast.LENGTH_SHORT).show();
            checked=false;
        }
        return checked;
    }

    private void sendComment(){
        Post post = new Post();
        post.setUserId(UUID.randomUUID().toString());
        post.setUserMobile(mComment.getUserMobile());
        post.setUserName(mComment.getUserName());
        post.setContent(mComment.getContent());
        post.setCommiter(AuthManager.getAuth().getUserId());

        getAPIService()
                .getService(PostService.class)
                .post(post)
                .subscribeOn(Schedulers.io())
                .flatMap(postRsp -> {
                    post.setId(postRsp.getData().getId());
                    post.setViews((long)Math.random()*10000);
                    post.setRefer((long)Math.random()*100);
                   return insert(post);
                })
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindToLifecycle())
                .subscribe(longs -> {
                    //ok
                    afterPost();
                    });
    }


    private void afterPost(){
        Toast.makeText(WorthActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
        setResult(RESULT_OK,getIntent());
        finish();
    }


    private Flowable<Long[]> insert(Post post){
        return Flowable.fromCallable(new Callable<Long[]>() {
            @Override
            public Long[] call() throws Exception {
                return mPostsVm.insert(post);
            }
        });
    }






    private void onClick(){
        // 设置免费
        RxCompoundButton.checkedChanges(mBinding.contentWorth.free)
                .subscribe(aBoolean -> {
                    if (aBoolean){
                        mComment.setPrice(null);
                    }
                });
        //光标位置
        RxTextView.textChanges(mBinding.contentWorth.price)
                .subscribe(charSequence -> mBinding.contentWorth.price.setSelection(charSequence.length()));
    }


    public void handlePriceClick(View view){
        mBinding.contentWorth.free.setChecked(false);
        Button button = (Button) view;
        mComment.setPrice(button.getText().toString());
    }
}
